﻿#region Using

using System;
using MvcMall.Framework.Extensions;
using MvcMall.Framework.UnitOfWork;
using NHibernate;
using SharpArch.Data.NHibernate;

#endregion

namespace MvcMall.Data.Repositories
{
    ///<summary>
    ///</summary>
    public abstract class DisposableResource : IDisposable
    {
        #region IDisposable Members

        ///<summary>
        ///</summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        ~DisposableResource()
        {
            Dispose(false);
        }

        protected virtual void Dispose(bool disposing)
        {
        }
    }

    public class NHUnitOfWork : DisposableResource, IUnitOfWork
    {
        private string _factoryKey;
        private bool _isDisposed;

        public NHUnitOfWork()
        {
            _factoryKey = NHibernateSession.DefaultFactoryKey;
        }

        #region IUnitOfWork Members

        public void Commit()
        {
            //if (_isDisposed)
            //{
            //    throw new ObjectDisposedException(GetType().Name);
            //}

            ITransaction currentTransaction = NHibernateSession.CurrentFor(_factoryKey).Transaction;

            if (currentTransaction.IsActive)
            {
                try
                {
                    //forces a flush of the current unit of work
                    currentTransaction.Commit();
                }
                catch
                {
                    currentTransaction.Rollback();
                    throw;
                }
                finally
                {
                    currentTransaction.Dispose();
                }
            }
        }

        public void Init(string factoryKey)
        {
            if (factoryKey.IsNotNullOrEmpty())
                _factoryKey = factoryKey;

            NHibernateSession.CurrentFor(_factoryKey).BeginTransaction();
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                _isDisposed = true;
            }

            base.Dispose(disposing);
        }
    }
}